<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="试卷名称" prop="paperName">
            <el-input
              v-model="queryParams.paperName"
              placeholder="请输入试卷名称"
              clearable
              @keyup.enter="handleQuery"
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="考试类型" prop="paperCategoryId">
            <el-select
              v-model="queryParams.paperCategoryId"
              placeholder="考试类型"
              @change="handleQuery"
            >
              <el-option
                v-for="item in paperCategoryList"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="daterangeCreateTime"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8"
          ><el-form-item label="试卷开始时间" prop="paperStartDate">
            <el-date-picker
              clearable
              v-model="queryParams.paperStartDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择试卷开始时间"
            >
            </el-date-picker> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="试卷结束时间" prop="paperEndDate">
            <el-date-picker
              clearable
              v-model="queryParams.paperEndDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择试卷结束时间"
            >
            </el-date-picker> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="">
            <el-button type="primary" :icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item></el-col
        >
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <div class="all-button">
        <div class="left-button">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              :icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPerm="['examManage:paperManage:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              :icon="Plus"
              @click="handleAdd"
              v-hasPerm="['examManage:paperManage:add']"
              >新增</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              :icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPerm="['examManage:paperManage:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              :icon="Download"
              @click="handleExport"
              v-hasPerm="['examManage:paperManage:export']"
              >导出</el-button
            >
          </el-col>
        </div>
        <div>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </div>
      </div>
    </el-row>

    <el-table
      v-loading="loading"
      :data="paperManageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="paperId" />
      <el-table-column label="试卷名称" align="center" prop="paperName" />
      <el-table-column label="总分数" align="center" prop="paperScore" />
      <el-table-column label="限时(分)" align="center" prop="paperTimeLimit" />
      <el-table-column
        label="试卷开始时间"
        align="center"
        prop="paperStartDate"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="试卷结束时间"
        align="center"
        prop="paperEndDate"
        width="180"
      >
      </el-table-column>
      <el-table-column label="考试类型" align="center" prop="paperCategoryId">
        <template #default="scope">
          {{
            paperCategoryList.find(
              (m) => m.dictValue == scope.row.paperCategoryId
            )?.dictLabel
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        :width="
          currentUser.roles && currentUser.roles.includes('超级管理员') > 0
            ? '160px'
            : '60px'
        "
      >
        <template #default="scope">
          <el-tooltip
            content="编辑考题"
            placement="top"
            v-if="!scope.row.examIsEnd"
          >
            <el-button
              link
              type="primary"
              :icon="EditPen"
              v-hasPerm="['examManage:paperManage:edit']"
              @click="showQuestionList(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.isHasQuestion || !scope.row.examIsEnd"
            content="参加考试"
            placement="top"
          >
            <el-button
              type="primary"
              link
              :icon="CirclePlus"
              @click="handleJoinPaper(scope.row)"
              v-hasPerm="['examManage:paperManage:joinPaper']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="编辑"
            placement="top"
            v-if="!scope.row.examIsEnd"
          >
            <el-button
              link
              type="primary"
              :icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPerm="['examManage:paperManage:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
            v-if="!scope.row.examIsEnd"
          >
            <el-button
              link
              type="primary"
              :icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPerm="['examManage:paperManage:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷管理对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" append-to-body>
      <el-form
        ref="paperManageRef"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <!-- <el-form-item label="图标地址" prop="logoUrl">
          <el-input v-model="form.logoUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="paperName">
              <el-input
                v-model="form.paperName"
                placeholder="请输入试卷名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="考试类型" prop="paperCategoryId">
              <el-select v-model="form.paperCategoryId" placeholder="考试类型">
                <el-option
                  v-for="item in paperCategoryList"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总分数" prop="paperScore">
              <el-input v-model="form.paperScore" placeholder="请输入总分数">
                <template #append>分</template></el-input
              >
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="限时" prop="paperTimeLimit">
              <el-input v-model="form.paperTimeLimit" placeholder="请输入限时">
                <template #append>分钟</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="试卷开始时间" prop="paperStartDate">
              <el-date-picker
                clearable
                v-model="form.paperStartDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择试卷开始时间"
              >
              </el-date-picker> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="试卷结束时间" prop="paperEndDate">
              <el-date-picker
                clearable
                v-model="form.paperEndDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择试卷结束时间"
              >
              </el-date-picker> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="试卷描述" prop="paperDescription">
          <el-input
            v-model="form.paperDescription"
            type="textarea"
            placeholder="请输入内容"
            :rows="3"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                :rows="3"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- PaperAddQuestion -->
    <paper-add-question
      v-model="isShowQuestion"
      :dialogVisible="isShowQuestion"
      :paperId="paperId"
      :paperTotal="paperTotal"
      :dialogTitle="dialogTitle"
      @initList="getList"
    />
  </div>
</template>

<script setup name="PaperManage">
import {
  listPaperManage,
  getPaperManage,
  delPaperManage,
  addPaperManage,
  updatePaperManage,
} from "@/api/examManage/paperManage";
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from "vue";
import {
  Search,
  Plus,
  Refresh,
  Edit,
  Download,
  Delete,
  EditPen,
  CirclePlus,
} from "@element-plus/icons-vue";
import PaperAddQuestion from "./components/PaperAddQuestion";
import { listDictData } from "@/api/sys/dictData";
import { useRouter } from "vue-router";
import { listByPaperId } from "@/api/examManage/question";

const { proxy } = getCurrentInstance();
const router = useRouter();
const paperGradeList = ref([]);
const isShowQuestion = ref(false);
const paperManageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const paperId = ref(-1);
const paperTotal = ref(0);
const dialogTitle = ref("");
const querySelectParams = ref({
  pageNum: 1,
  pageSize: 10,
  params: {},
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    logoUrl: null,
    paperName: null,
    paperStartDate: null,
    paperEndDate: null,
    paperCategoryId: null,
    createTime: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
const currentUser = ref({});
const paperCategoryList = ref([]);
const handleJoinPaper = (row) => {
  sessionStorage.setItem("id", row.paperId);
  router.push(`/examManage/paperManage/joinPaper`);
};
const initData = async () => {
  await listDictData({
    pageNum: 1,
    pageSize: 20,
    dictType: "paper_category",
  }).then((res) => {
    paperCategoryList.value = res.data.rows;
  });
  if (sessionStorage.getItem("currentUser")) {
    currentUser.value = JSON.parse(sessionStorage.getItem("currentUser"));
  }
};
/**
 * 新增考题
 */
const showQuestionList = (row) => {
  isShowQuestion.value = true;
  dialogTitle.value = "新增考题";
  paperId.value = row.paperId;
  paperTotal.value = row.paperScore;
};
/** 查询试卷管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listPaperManage(queryParams.value).then((response) => {
    let _objRes = response.data.rows;
    _objRes.map(async (t) => {
      t.examIsEnd = new Date().getTime() > new Date(t.paperEndDate).getTime();
      t.isDelete = new Date().getTime() > new Date(t.paperStartDate).getTime();
      querySelectParams.value.params.paperId = t.paperId;
      const questionSelectRes = await listByPaperId(querySelectParams.value);
      t.isHasQuestion = !!questionSelectRes.data.rows.length;

      return t;
    });

    paperManageList.value = _objRes;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    paperId: null,
    logoUrl: null,
    paperName: null,
    paperDescription: null,
    paperScore: null,
    paperTimeLimit: null,
    paperStartDate: null,
    paperEndDate: null,
    paperCategoryId: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("paperManageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.paperId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加试卷管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _paperId = row.paperId || ids.value;
  getPaperManage(_paperId).then((response) => {
    let _data = response.data.data;
    _data.paperCategoryId = _data.paperCategoryId + "";
    form.value = _data;
    open.value = true;
    title.value = "修改试卷管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paperManageRef"].validate((valid) => {
    if (valid) {
      if (form.value.paperId != null) {
        updatePaperManage(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPaperManage(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _paperIds = row.paperId || ids.value;
  proxy.$modal
    .confirm('是否确认删除试卷管理编号为"' + _paperIds + '"的数据项？')
    .then(function () {
      return delPaperManage(_paperIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "examManage/paperManage/export",
    {
      ...queryParams.value,
    },
    `paperManage_${new Date().getTime()}.xlsx`
  );
}
initData();
onMounted(() => {
  getList();
});
</script>
